<template>
	<el-breadcrumb class="app-breadcrumb" :separator-icon="ArrowRight">
		<el-breadcrumb-item v-for="(item, index) in levelList" :key="item.path">
			<!-- 自定义的title名称 -->
			<span v-if="item.meta.title.includes('custom')">{{ metaTitle || item.meta.title }}</span>
			<!-- 菜单中配置的title名称 -->
			<span v-else-if="item.redirect === 'noRedirect' || index == levelList.length - 1" class="no-redirect">
				{{ item.meta.title }}
			</span>
			<a v-else @click.prevent="handleLink(item)">{{ item.meta.title }}</a>
		</el-breadcrumb-item>
	</el-breadcrumb>
</template>

<script setup>
import { ArrowRight } from "@element-plus/icons-vue";
import usePermissionStore from "@/store/modules/permission";
import useSettingsStore from "@/store/modules/settings";
const permissionStore = usePermissionStore();
const metaTitle = computed(() => useSettingsStore().metaTitle);
const title = computed(() => useSettingsStore().title);

const levelList = ref([]);

// 所有的路由信息
const routeList = computed(() => permissionStore.sidebarRouters);

watch(
	() => title.value,
	() => {
		setLevelList();
	},
	{
		immediate: false
	}
);

// 定义递归函数来查找路由对象及其父级路径
function findRouteWithParents(routes, targetTitle, currentPath = []) {
	// 遍历当前层级的所有路由对象
	for (let i = 0; i < routes.length; i++) {
		// 首页做特殊处理
		if (targetTitle === "首页") {
			return [{ meta: { title: "首页" } }];
		}

		// 个人中心页做特殊处理
		if (targetTitle === "个人中心") {
			return [{ meta: { title: "个人中心" } }];
		}

		const route = routes[i];
		// 如果当前路由对象有 children 数组，则先搜索 children
		if (route.children && route.children.length > 0) {
			const foundInChildren = findRouteWithParents(route.children, targetTitle, [...currentPath, route]);
			if (foundInChildren) {
				return foundInChildren; // 找到子节点中的匹配，返回它
			}
		}

		// 然后再检查当前路由对象本身的 title 是否与 targetTitle 匹配
		if (route.meta && route.meta.title === targetTitle) {
			return [...currentPath, route]; // 找到匹配的路由对象，返回当前路径
		}
	}

	return null; // 如果没有找到匹配的路由对象，返回 null
}

function setLevelList() {
	const paths = findRouteWithParents(routeList.value, title.value);
	const length = paths.length;
	if (length < 3) {
		levelList.value = paths;
		return;
	}
	// hack 方法，防止子路径重名
	const lastPath = paths[length - 1];
	const lastTwoPath = paths[length - 2];
	if (lastPath.meta.title === lastTwoPath.meta.title) {
		levelList.value = paths.slice(0, length - 1);
	} else {
		levelList.value = paths;
	}
}

setLevelList();
</script>

<style lang="scss" scoped>
.app-breadcrumb.el-breadcrumb {
	display: inline-block;
	font-size: 14px;
	.el-breadcrumb__item:last-child {
		:deep(.el-breadcrumb__inner) {
			color: var(--el-color-primary);
			cursor: text;
		}
	}
}
</style>
